﻿using System;
using System.Drawing;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media.Imaging;
using Hardcodet.Wpf.TaskbarNotification;
using KlavoNotifications.ViewModels.Notification;
using KlavoNotifications.ViewModels.Tray;
using KlavoNotifications.Views;
using KlavoNotifications.Views.Notification;
using System.Linq;

namespace KlavoNotifications.Utils
{
    public class TaskBar
    {
        private TaskbarIcon _tbi;

        public void Start()
        {
            _tbi = new TaskbarIcon();
            _tbi.PopupActivation = PopupActivationMode.LeftOrDoubleClick;
            _tbi.MenuActivation = PopupActivationMode.RightClick;

            SetRunningState();

            var viewModel = new TrayListViewModel();

            TrayList trayList = new TrayList(viewModel);
            _tbi.TrayPopup = trayList;

            ContextMenu menu = new ContextMenu();
            MenuItem exit = new MenuItem();
            exit.Header = "Выход";
            exit.Icon = new System.Windows.Controls.Image
            {
                Source = new BitmapImage(new Uri("pack://application:,,,/KlavoNotifications;component/Icons/quit.png")),
                Width = 24,
                Height = 24,
            };

            exit.Click += (s, ar) => Application.Current.Shutdown();
            menu.Items.Add(exit);

            _tbi.ContextMenu = menu;

        }

        private Icon IconFromString(string fileName)
        {
            var si = Application.GetResourceStream(new Uri(String.Format(@"pack://application:,,,/KlavoNotifications;component/Icons/{0}", fileName)));
            if (si != null)
            {
                using (Stream iconStream = si.Stream)
                {
                    return new Icon(iconStream);
                }
            }

            return null;
        }

        public void SetRunningState()
        {
            //  _tbi.ToolTipText = "Запущен";
            _tbi.Icon = IconFromString("klav.ico");
        }

        public void SetStoppedState()
        {
            //   _tbi.ToolTipText = "Остановлен";
            _tbi.Icon = IconFromString("klavOff.ico");
        }

        public void ShowBalloon(BalloonViewModel viewModel)
        {
            if (Environment.OSVersion.Version.Major > 5)
                _tbi.ShowCustomBalloon(new BalloonView(viewModel), PopupAnimation.None, 6000);
            else
            {
                string message = String.Join(Environment.NewLine, viewModel.Items.Select(r => r.Voc));
                _tbi.ShowBalloonTip("Klavonotification", message, BalloonIcon.Info);
            }
        }

        public void CloseBalloon()
        {
            _tbi.CloseBalloon();
        }
    }
}